<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PS套索工具模拟</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#1e40af',
                        neutral: '#f3f4f6',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .tool-active {
                @apply bg-primary text-white;
            }
            .canvas-container {
                @apply relative w-full h-[600px] bg-gray-100 overflow-hidden;
            }
            .toolbar {
                @apply flex flex-col bg-gray-800 text-white p-2 space-y-3 rounded-lg shadow-lg;
            }
            .tool-button {
                @apply p-2 rounded hover:bg-gray-700 transition-all duration-200 flex items-center justify-center;
            }
            .canvas-wrapper {
                @apply flex justify-center items-center w-full h-full;
            }
            .mode-button {
                @apply px-2 py-1 text-xs rounded transition-all duration-200 text-center;
            }
            .mode-active {
                @apply bg-primary text-white;
            }
        }
    </style>
</head>
<body class="bg-gray-900 font-inter text-gray-100 min-h-screen flex flex-col">
    <header class="bg-gray-800 shadow-md py-4 px-6 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-paint-brush text-primary text-2xl"></i>
            <h1 class="text-xl font-bold">套索工具模拟</h1>
        </div>
        <div class="flex items-center space-x-4">
            <button id="saveBtn" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded transition-all duration-200 flex items-center">
                <i class="fa fa-save mr-2"></i>保存选区
            </button>
            <button id="uploadBtn" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded transition-all duration-200 flex items-center">
                <i class="fa fa-upload mr-2"></i>上传图片
            </button>
        </div>
    </header>

    <main class="flex-1 p-6 flex flex-col md:flex-row gap-6">
        <div class="w-full md:w-64">
            <div class="toolbar">
                <h3 class="text-center font-semibold text-sm uppercase tracking-wider mb-2">工具</h3>
                <div class="space-y-1">
                    <button id="polygonTool" class="tool-button tool-active" title="多边形套索工具 (P)">
                        <i class="fa fa-pencil-square-o"></i>
                    </button>
                </div>
                
                <!-- 添加选区模式选项 -->
                <div class="mt-6">
                    <h3 class="text-center font-semibold text-sm uppercase tracking-wider mb-2">选区模式</h3>
                    <div class="grid grid-cols-2 gap-1">
                        <button id="newSelection" class="mode-button mode-active" title="新建选区">
                            <i class="fa fa-square-o"></i>
                        </button>
                        <button id="addSelection" class="mode-button" title="添加到选区 (Shift)">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 选区信息 -->
                <div class="mt-6 p-2 bg-gray-700 rounded">
                    <h3 class="text-center font-semibold text-sm uppercase tracking-wider mb-2">选区信息</h3>
                    <div class="text-xs space-y-1">
                        <p>状态: <span id="selectionStatus">无选区</span></p>
                        <p>模式: <span id="currentMode">新建</span></p>
                        <p>点数量: <span id="pointCount">0</span></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="flex-1">
            <div class="canvas-container rounded-lg shadow-xl">
                <div class="canvas-wrapper">
                    <canvas id="imageCanvas" class="border-2 border-gray-300 rounded shadow-lg"></canvas>
                </div>
            </div>
        </div>
    </main>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 获取Canvas元素和绘图上下文
            const canvas = document.getElementById('imageCanvas');
            const ctx = canvas.getContext('2d');
            
            // 设置Canvas尺寸
            canvas.width = 800;
            canvas.height = 500;
            
            // 工具状态
            let isDrawing = false;
            let currentPoints = []; // 当前正在绘制的点
            let savedSelections = []; // 已保存的选区集合，每个元素是一个独立的选区点数组
            let selectionMode = 'new'; // 选区模式: new, add, subtract
            let backgroundImage = null;
            let currentTool = 'polygon'; // 只保留多边形套索工具
            
            // 生成示例图像（网格背景）
            function drawGrid() {
                const gridSize = 20;
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.strokeStyle = '#eeeeee';
                ctx.lineWidth = 1;
                
                // 绘制垂直线
                for (let x = 0; x < canvas.width; x += gridSize) {
                    ctx.beginPath();
                    ctx.moveTo(x, 0);
                    ctx.lineTo(x, canvas.height);
                    ctx.stroke();
                }
                
                // 绘制水平线
                for (let y = 0; y < canvas.height; y += gridSize) {
                    ctx.beginPath();
                    ctx.moveTo(0, y);
                    ctx.lineTo(canvas.width, y);
                    ctx.stroke();
                }
            }
            
            // 绘制背景图片
            function drawBackgroundImage() {
                if (backgroundImage) {
                    ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
                } else {
                    drawGrid();
                }
            }
            
            // 绘制已保存的选区
            function drawSavedSelection() {
                for (const selection of savedSelections) {
                    if (selection.length < 3) continue;
                    
                    ctx.save();
                    ctx.beginPath();
                    ctx.moveTo(selection[0].x, selection[0].y);
                    
                    for (let i = 1; i < selection.length; i++) {
                        ctx.lineTo(selection[i].x, selection[i].y);
                    }
                    
                    ctx.closePath();
                    
                    // 填充半透明蓝色
                    ctx.fillStyle = 'rgba(59, 130, 246, 0.2)';
                    ctx.fill();
                    
                    // 绘制选区边界（虚线）
                    ctx.strokeStyle = '#3b82f6';
                    ctx.lineWidth = 2;
                    ctx.setLineDash([5, 5]);
                    ctx.stroke();
                    
                    ctx.restore();
                }
            }
            
            // 绘制当前正在绘制的选区
            function drawCurrentSelection() {
                // 首点高亮显示（无论有几个点）
                if (currentPoints.length > 0) {
                    ctx.save();
                    ctx.beginPath();
                    ctx.arc(currentPoints[0].x, currentPoints[0].y, 6, 0, 2 * Math.PI);
                    ctx.fillStyle = '#ef4444'; // 红色高亮
                    ctx.fill();
                    ctx.lineWidth = 2;
                    ctx.strokeStyle = '#fff';
                    ctx.stroke();
                    ctx.restore();
                }
                if (currentPoints.length < 2) return;
                
                ctx.save();
                ctx.beginPath();
                ctx.moveTo(currentPoints[0].x, currentPoints[0].y);
                
                for (let i = 1; i < currentPoints.length; i++) {
                    ctx.lineTo(currentPoints[i].x, currentPoints[i].y);
                }

                // 多边形工具需要手动闭合路径
                if (currentPoints.length >= 3) {
                    ctx.closePath();
                }
                
                // 填充和描边逻辑
                if (currentPoints.length >= 3) {
                    ctx.fillStyle = selectionMode === 'add' ? 'rgba(34, 197, 94, 0.2)' : 'rgba(59, 130, 246, 0.2)';
                    ctx.fill();
                }
                
                ctx.strokeStyle = selectionMode === 'add' ? '#22c55e' : '#3b82f6';
                ctx.lineWidth = 2;
                ctx.setLineDash([5, 5]);
                ctx.stroke();
                ctx.restore();
            }
            
            // 检查路径是否闭合（首尾相连）
            function isClosedPath() {
                return currentPoints.length >= 3;
            }
            
            // 清除当前正在绘制的选区
            function clearCurrentSelection() {
                currentPoints = [];
                updateSelectionInfo();
            }
            
            // 清除所有选区
            function clearAllSelections() {
                currentPoints = [];
                savedSelections = [];
                redrawCanvas();
                updateSelectionInfo();
            }
            
            // 重绘Canvas
            function redrawCanvas() {
                drawBackgroundImage();
                drawSavedSelection();
                drawCurrentSelection();
            }
            
            // 更新选区信息显示
            function updateSelectionInfo() {
                document.getElementById('pointCount').textContent = currentPoints.length;
                
                // 更新状态
                if (savedSelections.length > 0) {
                    document.getElementById('selectionStatus').textContent = '已创建';
                } else {
                    document.getElementById('selectionStatus').textContent = '无选区';
                }
                
                // 更新模式显示
                switch(selectionMode) {
                    case 'new':
                        document.getElementById('currentMode').textContent = '新建';
                        break;
                    case 'add':
                        document.getElementById('currentMode').textContent = '添加';
                        break;
                }
            }
            
            // 应用选区操作
            function applySelection() {
                if (currentPoints.length < 3) {
                    return false;
                }
                // 只要有三个点以上就允许闭合
                switch(selectionMode) {
                    case 'new':
                        savedSelections = [[...currentPoints]];
                        break;
                    case 'add':
                        savedSelections.push([...currentPoints]);
                        break;
                }
                currentPoints = [];
                return true;
            }
            
            // 判断点是否在多边形内部（用于减法操作）
            function isPointInPolygon(point, polygon) {
                let inside = false;
                for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
                    const xi = polygon[i].x, yi = polygon[i].y;
                    const xj = polygon[j].x, yj = polygon[j].y;
                    
                    const intersect = ((yi > point.y) !== (yj > point.y))
                        && (point.x < (xj - xi) * (point.y - yi) / (yj - yi) + xi);
                    if (intersect) inside = !inside;
                }
                return inside;
            }
            
            // 修改保存选区的函数
            document.getElementById('saveBtn').addEventListener('click', function() {
                if (savedSelections.length === 0) {
                    alert('请先绘制一个闭合的选区');
                    return;
                }
                
                // 创建选区图像数据
                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = canvas.width;
                tempCanvas.height = canvas.height;
                const tempCtx = tempCanvas.getContext('2d');
                
                // 绘制背景
                if (backgroundImage) {
                    tempCtx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
                } else {
                    // 绘制网格
                    const gridSize = 20;
                    tempCtx.fillStyle = '#ffffff';
                    tempCtx.fillRect(0, 0, canvas.width, canvas.height);
                    
                    tempCtx.strokeStyle = '#eeeeee';
                    tempCtx.lineWidth = 1;
                    
                    for (let x = 0; x < canvas.width; x += gridSize) {
                        tempCtx.beginPath();
                        tempCtx.moveTo(x, 0);
                        tempCtx.lineTo(x, canvas.height);
                        tempCtx.stroke();
                    }
                    
                    for (let y = 0; y < canvas.height; y += gridSize) {
                        tempCtx.beginPath();
                        tempCtx.moveTo(0, y);
                        tempCtx.lineTo(canvas.width, y);
                        tempCtx.stroke();
                    }
                }
                
                // 创建一个掩码Canvas来绘制所有选区
                const maskCanvas = document.createElement('canvas');
                maskCanvas.width = canvas.width;
                maskCanvas.height = canvas.height;
                const maskCtx = maskCanvas.getContext('2d');
                
                // 清除掩码Canvas
                maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height);
                
                // 在掩码Canvas上绘制所有选区
                for (const selection of savedSelections) {
                    maskCtx.beginPath();
                    maskCtx.moveTo(selection[0].x, selection[0].y);
                    for (let i = 1; i < selection.length; i++) {
                        maskCtx.lineTo(selection[i].x, selection[i].y);
                    }
                    maskCtx.closePath();
                    maskCtx.fillStyle = 'black';
                    maskCtx.fill();
                }
                
                // 将背景应用掩码
                tempCtx.globalCompositeOperation = 'destination-in';
                tempCtx.drawImage(maskCanvas, 0, 0);
                
                // 创建下载链接
                const link = document.createElement('a');
                link.download = 'selection.png';
                link.href = tempCanvas.toDataURL('image/png');
                link.click();
            });
            
            // 上传图片
            document.getElementById('uploadBtn').addEventListener('click', function() {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = 'image/*';
                input.onchange = function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const img = new Image();
                            img.onload = function() {
                                backgroundImage = img;
                                redrawCanvas();
                            };
                            img.src = e.target.result;
                        };
                        reader.readAsDataURL(file);
                    }
                };
                input.click();
            });
            
            // 鼠标按下事件
            canvas.addEventListener('mousedown', function(e) {
                const rect = canvas.getBoundingClientRect();
                const x = e.clientX - rect.left;
                const y = e.clientY - rect.top;
                currentPoints.push({x, y});
                redrawCanvas();
                updateSelectionInfo();
            });

            // 鼠标双击事件（用于闭合多边形）
            canvas.addEventListener('dblclick', function() {
                if (currentPoints.length >= 3) {
                    applySelection();
                    redrawCanvas();
                }
            });
            
            // 鼠标移动事件
            // 移除lasso相关逻辑，不再处理mousemove
            
            // 鼠标释放事件
            // 移除lasso相关逻辑，不再处理mouseup
            
            // 选区模式按钮事件
            document.getElementById('newSelection').addEventListener('click', function() {
                selectionMode = 'new';
                setActiveModeButton('newSelection');
                updateSelectionInfo();
            });
            
            document.getElementById('addSelection').addEventListener('click', function() {
                selectionMode = 'add';
                setActiveModeButton('addSelection');
                updateSelectionInfo();
            });

            // 工具按钮事件
            // 只保留polygonTool按钮，且始终激活
            document.getElementById('polygonTool').addEventListener('click', function() {
                // This button is always active, so no need to set active class here
            });
            
            // 设置激活的模式按钮样式
            function setActiveModeButton(id) {
                document.querySelectorAll('.mode-button').forEach(btn => {
                    btn.classList.remove('mode-active');
                });
                document.getElementById(id).classList.add('mode-active');
            }

            // 设置激活的工具按钮样式
            function setActiveToolButton(id) {
                document.querySelectorAll('.tool-button').forEach(btn => {
                    btn.classList.remove('tool-active');
                });
                document.getElementById(id).classList.add('tool-active');
            }
            
            // 初始化
            drawGrid();
            updateSelectionInfo();
        });
    </script>
</body>
</html>